package com.qf.user.manager.service.impl;

import com.qf.common.model.QfUser;
import com.qf.user.manager.bean.LoginUser;
import com.qf.user.manager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义UserDetailService实现类, 实现SpringSecurity的UserDetailsService接口
 * @author 千锋健哥
 */
@Service(value = "userDetailServiceImpl")
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1. 根据用户名到数据库获取用户对象
        QfUser qfUser = userService.getUserByUserName(username);

        if (qfUser == null) {
            //2. 如果获取不到抛出提示异常
            throw new UsernameNotFoundException("该用户不存在!");
        } else {
            //3. 如果能够获取到, 在根据用户名获取用户的权限集合
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            List<String> menuList = userService.findUserMenuByUserName(qfUser.getUserName());
            if (menuList != null) {
                for (String menu : menuList) {
                    //4. 将权限集合封装到SpringSecurity的权限集合对象中
                    authorities.add(new SimpleGrantedAuthority(menu));
                }
            }

            //5. 将权限集合以及当前用户对象, 封装成SpringSecurity的UserDetails实体对象返回
            LoginUser loginUser = new LoginUser(qfUser, authorities);
            return loginUser;
        }

    }

}
